package com.yeyoo.websocket.websocket;


import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by jinyifeng5969@163.com on 2020-11-02.
 */
@ServerEndpoint(value = "/connectWebSocket/{userId}")
@Component
public class WebServicePoint {


    private static ConcurrentHashMap<String, WebServicePoint> user = new ConcurrentHashMap<String, WebServicePoint>();
    private Session session;
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        String id = session.getId();
        this.session = session;
        user.put("1", this);
        System.out.println("连接成功");
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接断开");
    }
    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println(message);

    }
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public void sendMessagess(String message) {
        WebServicePoint webServicePoint = user.get("1");
        try {
            webServicePoint.sendMessage(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
